"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
require("./css/main.css");
var signalR = require("@microsoft/signalr");
var msgpack = require("@microsoft/signalr-protocol-msgpack");
var divMessages = document.querySelector("#divMessages");
var tbMessage = document.querySelector("#tbMessage");
var btnSend = document.querySelector("#btnSend");
var getMsg = document.querySelector("#getMsg");
var currentTime = document.querySelector("#currentTime");
var userName = new Date().getTime();
var url = "https://localhost:51541";
// 使用 stream 
var connection4 = new signalR.HubConnectionBuilder()
    .withUrl(url + "/hubs/streaming", { skipNegotiation: true, transport: signalR.HttpTransportType.WebSockets })
    //.withHubProtocol(new msgpack.MessagePackHubProtocol())
    .withAutomaticReconnect([0, 2000, 10000, 30000]) // 自动重连策略
    .build();
//connection4.start();
// 需要使用异步方法启动 但是我们还想让他立即执行，所以使用立即执行函数
(function () { return __awaiter(void 0, void 0, void 0, function () {
    var e_1;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                _a.trys.push([0, 2, , 3]);
                return [4 /*yield*/, connection4.start()];
            case 1:
                _a.sent();
                return [3 /*break*/, 3];
            case 2:
                e_1 = _a.sent();
                console.error(e_1.toString());
                return [3 /*break*/, 3];
            case 3: return [2 /*return*/];
        }
    });
}); })();
var loginToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoid2phQG1pY3Jvc29mdC5jb20iLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJBZG1pbiIsIkN1c3RvbUNsYWltIjoiQ3VzdG9tVmFsdWUiLCJleHAiOjE3NDgzNTIwNzksImlzcyI6IndqYSIsImF1ZCI6IndqYSJ9.6ONpM5f-ZAo0Ve-nRO2F5k78f1aCMRKuZOcK8eoMcJg";
var connection3 = new signalR.HubConnectionBuilder().withUrl(url + "/hubs/authorized", { accessTokenFactory: function () { return loginToken; } }).build();
connection3.start().catch(function (err) { return console.error(err); });
var connection2 = new signalR.HubConnectionBuilder().withUrl(url + "/hubs/clock").build();
// 服务器给客户端发送消息 时间是字符串格式
connection2.on("ShowTime", function (time) {
    //console.log("ShowTime", time);
    //console.log(typeof time);
    //var t = new Date(time);
    //currentTime.innerText = "  "+ t.toLocaleDateString()+" " +t.toLocaleTimeString();
    currentTime.innerText = time;
});
connection2.start().then(function () {
    console.log("Clock Hub started");
})
    .catch(function (err) { return console.error(err); });
var connection = new signalR.HubConnectionBuilder()
    .withUrl(url + "/hub")
    .withHubProtocol(new msgpack.MessagePackHubProtocol()) // 使用 MessagePack 协议
    .build();
connection.on("ReceiveMessage", function (username, message) {
    console.log(username, message);
    var messages = document.createElement("div");
    messages.innerHTML = "<div class=\"message-author\">".concat(username, "</div><div>").concat(message, "</div>");
    divMessages.appendChild(messages);
    divMessages.scrollTop = divMessages.scrollHeight;
});
// 服务器给客户端发送消息
connection.on("ReceiveMessage", function (req) {
    console.log("ReceiveMessage", req);
});
// 客户端给服务器发送消息
connection.on("GetMessage", function () { return __awaiter(void 0, void 0, void 0, function () {
    var promise;
    return __generator(this, function (_a) {
        promise = new Promise(function (resolve, reject) {
            setTimeout(function () {
                resolve("ok 来自客户端的消息");
            }, 100);
        });
        return [2 /*return*/, promise];
    });
}); });
connection.start().catch(function (err) { return document.write(err); });
tbMessage.addEventListener("keyup", function (e) {
    if (e.key === "Enter") {
        send();
    }
});
btnSend.addEventListener("click", send);
function send() {
    //connection.invoke("GetTotalLength", { parm1: "msg" })
    connection3.invoke("TestAuthorization");
    connection3.invoke("banUser", "wja");
    try {
        // 可以调用 CounterChannel 和 Counter 两个方法
        connection4.stream("CounterChannel", 10, 500)
            .subscribe({
            next: function (item) {
                console.log("Counter item:", item);
                var messages = document.createElement("div");
                messages.innerHTML = "<div class=\"message-author\">Counter</div><div>".concat(item, "</div>");
                divMessages.appendChild(messages);
                divMessages.scrollTop = divMessages.scrollHeight;
            },
            complete: function () {
                console.log("Counter stream completed");
                var messages = document.createElement("div");
                messages.innerHTML = "<div class=\"message-author\">Counter</div><div>Stream completed</div>";
                divMessages.appendChild(messages);
            },
            error: function (err) {
                console.error("Counter stream error:", err);
                var messages = document.createElement("div");
                messages.innerHTML = "<div class=\"message-author\">Counter</div><div>Error: ".concat(err, "</div>");
                divMessages.appendChild(messages);
            }
        });
    }
    catch (e) {
        console.error(e.toString());
    }
    connection.invoke("SendMessage", { UserName: userName, Message: tbMessage.value }).then(function () { return (tbMessage.value = ""); });
}
getMsg.addEventListener("click", function () { return __awaiter(void 0, void 0, void 0, function () {
    var subject, iteration, intervalHandler;
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                subject = new signalR.Subject();
                return [4 /*yield*/, connection4.send("UploadStream", subject)];
            case 1:
                _a.sent();
                iteration = 0;
                intervalHandler = setInterval(function () {
                    iteration++;
                    subject.next(iteration.toString());
                    if (iteration >= 10) {
                        subject.complete();
                        clearInterval(intervalHandler);
                    }
                }, 1000);
                return [2 /*return*/];
        }
    });
}); });
